<?php
/**
 * 文章列表
 *
 */
function & li($page_size = ADM_PAGESIZE) {
    global $_TABLES, $class_var, $cata_info, $timestamp,$G_admin_session_key;

    $view_var   = array();
    $tbl_main   = $_TABLES['members_mess'];

    $conn   = & get_db_conn();

    $where      = 'WHERE 1 ';
    
    // 关键字
    $key    = trim(@$_GET['key']);
    if($key != '') $where  .= "AND (title LIKE '%$key%')";

    // 审核
    $display = @(int)$_GET['display'];
    if($display == 1) {
        $where  .= "AND display = 1 ";
    } elseif($display == 2) {
        $where  .= "AND display = 0 ";
    }

    $is_ad  = @$_GET['is_ad'];
    if($is_ad == 1) {
        // 发布时间处理开始
        $begin_date = @$_GET['begin_date'];
        $end_date   = @$_GET['end_date'];
        if($begin_date == '') {
            $begin_date   = 0;
        } else {
            $tmp    = explode('-', $begin_date);
            $begin_date = mktime(0 ,0, 0,$tmp[1] ,$tmp[2], $tmp[0]);
        }
        if($end_date == '') {
            $end_date   = $timestamp;
        } else {
            $tmp        = explode('-', $end_date);
            $end_date   = mktime(23 ,59, 59,$tmp[1] ,$tmp[2], $tmp[0]);
        }
        $where .= "AND (pub_time >= '$begin_date' AND pub_time <= '$end_date' ) ";
    }


    // 分页处理开始
    $csql   = "SELECT COUNT(*) AS rs_count FROM $tbl_main $where";
    $rs     = $conn->GetOne($csql);


    $record_total   = @(int)$rs;
    $page_total     = ceil($record_total/$page_size);

    $page   = @(int)$_GET['page'];
    if($page < 1) $page = 1;
    if($page > $page_total && $page_total > 0) $page = $page_total;
    $offset = ($page - 1) * $page_size;
    $limit  = "LIMIT $offset, $page_size";

    $view_var['record_total']   = $record_total;
    $view_var['page_total']     = $page_total;
    $view_var['page']           = $page;
    $view_var['page_size']      = $page_size;
    // 分页处理完毕


    // 列表处理开始
    $order_by   = trim(@$_GET['orderby']);
    $order_desc = @(int)$_GET['desc'];
    
    $order_by_q  = substr($order_by,0,5);
    $order_by_h  = substr($order_by,5);

    if($order_by_q   == 'flag_') {
        $order_by   = $order_by_h;
    }
    $select_param   = '';
    $str_order_by   = '';
    if($order_by != '') {
        if($order_by > 0) {
            $order_desc = ($order_desc!=1)?'DESC':'ASC';
            $orderfield = 'f' . $order_by;
            $select_param   = ",((`flag` & $order_by ) = $order_by) AS $orderfield";
            $str_order_by   = "{$orderfield} {$order_desc},";
        } else {
            $order_desc = ($order_desc!=1)?'ASC':'DESC';
            $str_order_by = "`{$order_by}` {$order_desc}, ";
        }
    }


    $order  = "";
    if($cata_info['cata_type'] == 1) {
        $order  = "ORDER BY $str_order_by pub_date ASC, id ASC";
    } else {
        $order  = "ORDER BY $str_order_by id DESC";
    }

    $sql    = "SELECT * FROM $tbl_main $where $order ";
    //echo $sql;
    $rs = & $conn->PageExecute($sql,$page_size,$page);
    $view_var['record'] = $rs->GetRows();
    return $view_var;
}

function & read($id = 0) {
    global $_TABLES, $timestamp, $mod, $G_admin_session_key, $G_cfg, $G_big_integer;

    $view_var   = array();
    $tbl_main   = $_TABLES['members_mess'];
    $tbl_mem   = $_TABLES['members'];
    
    if($id > 0) {
        $conn       = & get_db_conn();
        $view_var   = $conn->GetRow("SELECT * FROM $tbl_main WHERE id = $id");
        if($view_var['uid']){
            $view_var['usernames']=$conn->GetOne("SELECT username FROM $tbl_mem WHERE uid = {$view_var['uid']}");
        }else{
            $view_var['usernames']='';
        }
    } else {
		$pub_userid    = $_SESSION[$G_admin_session_key]['uid'];
        $pub_username  = $_SESSION[$G_admin_session_key]['username'];
        $pub_realname  = $_SESSION[$G_admin_session_key]['realname'];
        // 看用户是否有审核权限
        $chk_userid    = $_SESSION[$G_admin_session_key]['uid'];
        $chk_username  = $_SESSION[$G_admin_session_key]['username'];
        $chk_realname  = $_SESSION[$G_admin_session_key]['realname'];
        $view_var   = array(
                'hits'    => 0,
                'display' => $G_cfg['article_cfg']['article_display_default'],
                'pub_userid'      => $pub_userid,
              'pub_username'    => $pub_username,
              'pub_realname'    => $pub_realname,
              'pub_time'        => $timestamp,
              'pub_date'        => $timestamp,
              'createtime'     => $timestamp,
              'modifytime'      => $timestamp,
              'chk_userid'      => $chk_userid,
              'chk_username'    => $chk_username,
              'chk_realname'    => $chk_realname,
              'chk_time'        => $timestamp,            
              );
    }
    return $view_var;
}


/**
 * @description
 *  文章详细内容，
 *  获取参数，验证参数，初始化参数
 * @author
 *  hotgun@163.com
 *
 * @param
 *  (integer)$upload 是否包含并处理上传部分，如果是单独审核的就不需要包含这块，
 * @return 
 *  (array)修改和添加能使用的数组
 */
function & request($upload = 1) {
    global $action, $timestamp, $G_big_integer, $_TABLES;
    $data   = $_POST['article'];
    $data['display']  = @(int)$data['display']; // 审核
    if($data['pub_date']) {
        $data['pub_date']   = strtotime($data['pub_date']);
    } else {
        $data['pub_date']   = $timestamp;
    }

    // 处理单双引号等问题
    $data = post_pre_process($data);
    
    if($data['username']){
        $conn       = & get_db_conn();
        $tbl_mem   = $_TABLES['members'];
        $data['uid']=$conn->GetOne("SELECT uid FROM $tbl_mem WHERE username ='{$data['username']}'");
        if(!$data['uid']){
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                        '该会员不存在，请更正！', 
                        __FILE__,
                        __LINE__);
        }
    }else{
        $data['uid']=0;
    }
    

    // 过滤HTML内容中被php转义后的字符 
    // 去掉双引号前的转移符，将转义后的单引号转换成&#39;
    if(isset($data['content']))
	$data['content']    = str_replace("\\\"", "\"", str_replace("\\'", "&#39;", $data['content']));

    $rule = array();
    $def_err = array();
    if($upload == 1) {
        $rule   = array(
            'title' => 'i_string|len:1:255', 
            );

        // 验证正确性
        $def_err= array(
            'title' => '“标题”必须填写，且长度必须在1～255个字符之间！', 
            );
    }
    
    $result = data_validator($data, $rule, $def_err);
    if($result === true) {
        // 其他逻辑错误检验
    } else {
        foreach($result as $v) {
            $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                        $v, 
                        __FILE__,
                        __LINE__);
        }
    }
    if($GLOBALS['ERR']->Count > 0) {
        return false;
    } else {
        return $data;
    }
}

function not_samerecord($uid, $title, $modify = 0) {
    global $_TABLES;

    $tbl_main   = $_TABLES['members_mess'];
    $conn       = & get_db_conn();
    $where      = '';
    if($modify){
        $where=' AND id<>'.$modify;
    }
    $rs = $conn->GetRow("SELECT COUNT(*) AS rs_count FROM $tbl_main WHERE title = '$title' AND uid = '$cid' $where ");
    if($rs['rs_count'] > 0) {
        $GLOBALS['ERR']->AddError(_ERROR_BUSINESS, 
                "系统中已经存在标题为<FONT COLOR=\"red\">{$title}</FONT>的通知，无法当前操作！", 
                __FILE__,
                __LINE__);
        return false;
    }
    return true;
}


/**
 * @description
 *  添加文章内容
 * @author
 *  hotgun@163.com
 *
 * @return 
 *  (array)供主控部分使用的返回数据
 */
function add() {
    global $_TABLES, $timestamp, $mod, $class_var, $G_admin_session_key, $G_cfg;

    $tbl_article        = $_TABLES['members_mess'];

    $result = & request();
    if($result !== false) {
        $conn   = & get_db_conn();
        if(not_samerecord($result['uid'], $result['title'])) {
            // 如果没有同名纪录
            // 创建者/审核者等数据
            $result['pub_userid']   = $_SESSION[$G_admin_session_key]['uid'];
            $result['pub_username'] = $_SESSION[$G_admin_session_key]['username'];
            $result['pub_realname'] = $_SESSION[$G_admin_session_key]['realname'];
            if($conn->AutoExecute($tbl_article,$result,'INSERT')) {
                $id    = $conn->Insert_ID();
                $re = array('id'=>$id);
                return $re;
            }
        }
    }
    return false;
}


function modify() {
    global $_TABLES, $timestamp, $class_var, $G_admin_session_key;
    $tbl_article        = $_TABLES['members_mess'];
    $result = & request();
    if($result !== false) {
        $conn   = & get_db_conn();
        unset($result['pub_hour']);
        unset($result['pub_min']);
        unset($result['pub_sec']);
        // 先查看是否有同名记录
        if(not_samerecord($result['uid'], $result['article_title'], $result['id'])) {
            if($conn->AutoExecute($tbl_article,$result,'UPDATE', 'id=' . $result['id'] )) {
                // 返回到控制器的内容
                $re = array('id'=>$result['id']);
                return $re;
            }
        }
    }
}

function check_batch($check) {
    global $_TABLES, $timestamp, $class_var, $G_admin_session_key;
    $tbl_article        = $_TABLES['members_mess'];
    if(@(int)$check < 1) {
        $check  = 0;
        $checklang  = '取消审核';
    } else {
        $check  = 1;
        $checklang  = '通过审核';
    }

    $item_id    = array_join_comma($_POST['item_id']);
    if($item_id != '') {
        $conn   = & get_db_conn();

        $update_sql = "update $tbl_article SET 
            $sql_append
            display = $check 
            WHERE id IN ($item_id)";
        if($conn->Execute($update_sql)) {
            js_success('指定文章' . $checklang . '成功！');
        }
    }
    exit();
}

/**
 * @description
 *  审核单篇文章
 * 
 * @author
 *  hotgun@163.com
 */
function check() {
    global $_TABLES, $timestamp, $class_var, $G_admin_session_key;

    $tbl_article        = $_TABLES['members_mess'];

    $result = request(0);
    if($result !== false) {
        $conn   = & get_db_conn();

        if(@(int)$result['display'] == 1) {
            
        } else {
            $result['display'] = 0;
        }
        if($conn->AutoExecute($tbl_article,$result,'UPDATE', 'id=' . $result['id'] )) {
            return $result['id'];
        }
    }
}

function del() {
    global $_TABLES, $cfg_cache;
    $tbl_article = $_TABLES['members_mess'];

    $deltype    = trim(@$_POST['deltype']);
    if($deltype == 'all') {
        // 删除POST传递过来的 item_id 
        // 批量删除
        $str_in = array_join_comma($_POST['item_id']);
    } else {
        // get传递过来的删除 单条删除
        $item_id= @(int)$_GET['item_id'];
        $str_in = $item_id;
    }
$conn   = & get_db_conn();
    if($str_in != '') {
        $sql    = "DELETE FROM $tbl_article 
                    WHERE id IN ({$str_in}) ";
        if($conn->Execute($sql)) {
			js_success('删除指定文章成功！');
        }
    }
}
?>